<template>
    <div class="flex flex-col h-full bookmenu">
        <div class="flex-1 ">
            <el-tree ref="treeRef" :props="defaultProps" node-key="id" :data="bookmenu" draggable
                @node-drag-end="handleDragEnd" default-expand-all highlight-current :expand-on-click-node="false"
                :allow-drop="allowDrop">
                <template v-slot="{ node, data }">
                    <span class="flex flex-row items-center justify-between flex-1">
                        <span>{{ data.text }}</span>
                        <span class="flex-1 mx-2" style="height:1px;background:#555">
                        </span>
                        <span>
                            {{ pageNumbers(data).join() }}
                        </span>
                        <span class="mr-2">
                            <el-dropdown size="small">
                                <span class="el-dropdown-link">
                                    <el-icon class="el-icon--right" color="#fff"><arrow-down/></el-icon>
                                </span>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        
                                        <el-dropdown-item :icon="Plus" @click="addChildNode(data)">增加</el-dropdown-item>
                                        <el-dropdown-item :icon="Edit" v-if="data.canEdit"
                                            @click="editNode(data)">编辑</el-dropdown-item>
                                        <el-dropdown-item :icon="Delete" v-if="data.canDel"
                                            @click="delNode(node, data)">删除</el-dropdown-item>
                                        <el-dropdown-item :icon="View" @click="openPage(data)" v-if="data.pageIds.length>0">跳转到页面</el-dropdown-item>
                                        <el-dropdown-item :icon="Link" @click="linkSource(data)"  v-if="data.canEdit">挂接资源</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </span>
                    </span>

                </template>
            </el-tree>
        </div>

        <div class="flex flex-row justify-between px-2 py-2 buttons" style="border-top:1px solid #000">

        </div>
    </div>
    <el-dialog v-model="dialogNodeEditVisible" draggable title="修改节点">
        <div class="flex flex-row">
            <div class="flex-1 form">
                <el-form :model="editingNode" label-width="50px">
                    <el-form-item label="名称">
                        <el-input v-model="editingNode.text" />
                    </el-form-item>
                    <el-form-item label="页码">
                        <div class="flex flex-row flex-wrap">
                            <el-tag class="m-1 cursor-pointer" size="small" :type="page.selected ? '' : 'info'"
                                style="width:30px;" v-for="(page, index) in thisPages" :key="index"
                                @click="onPageClick(page)">{{ page.pageNum }}</el-tag>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div class="pages"></div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogNodeEditVisible = false">取消</el-button>
                <el-button type="primary" @click="dialogSubmit">提交</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog width="60%" v-model="dialogLinkSourceVisible" draggable :title="'【资源挂接】'+linkSourceData.title">
        <LinkSourceVue :link-type="linkSourceData.linkType" :link-id="linkSourceData.linkId"></LinkSourceVue>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'

import LinkSourceVue from '@/views/wisdbook/marker/linksource/index.vue'
import { ElMessage, ElTree } from 'element-plus'
import { storeToRefs } from "pinia";
import { useBookEditorStore, type Page, type BookMenu } from "@/stores/modules/wisdbookMarker";
import type { AllowDropType, NodeDropType } from 'element-plus/es/components/tree/src/tree.type';
import type { TreeNode } from 'element-plus/es/components/tree-v2/src/types';
import { addMenu, delMenu, updateMenu } from "@/api/wisdbook/menu";
import { Edit, Plus, Delete,View,Link } from '@element-plus/icons-vue'
const editorStore = useBookEditorStore();
let { bookmenu, pages, bookId, bookName} = storeToRefs(editorStore);
const dialogNodeEditVisible = ref(false)
const dialogLinkSourceVisible = ref(false)

const linkSourceData=reactive({
    title:'',
    linkType:'1',
    linkId:'0'
})

const treeRef = ref<InstanceType<typeof ElTree>>()
const defaultProps = {
    children: 'children',
    label: 'text'
}
export interface CheckerPage extends Page {
    selected: boolean;
}
let editingNode: any = ref(null)
let thisPages = ref(pages.value as CheckerPage[])
//添加跟目录
// if (bookmenu.value.length == 0) {
//     bookmenu.value.push({
//         id: 0,
//         pid: 0,
//         text: bookName.value,
//         bookId: bookId.value,
//         pageIds: [],
//         canDel: false,
//         canEdit: false,
//         canDrag: false,
//         sort: 1,
//         children: []
//     })
// }

const openPage = (node: BookMenu) => {
    console.log("点击：", node);
    let pageIds=node.pageIds
    let ids=pageIds.split(',');
    if(ids.length>0&&ids[0]!=''){
        editorStore.setPageId(Number(ids[0]))
    }else{
        ElMessage({message: '目录没有设定页码，无法跳转',type: 'error',})
    }
}

const linkSource=(node: BookMenu)=>{
    console.log("点击：", node);
    linkSourceData.linkId=node.id+''
    linkSourceData.title=node.text
    dialogLinkSourceVisible.value=true
}

/** 添加节点 */
const addChildNode = (node: BookMenu) => {
    // let node = treeRef.value!.getCurrentNode()
    console.log("父节点：", node);
    const newChild: BookMenu = {
        id: 0,
        pid: node.id,
        text: "新节点",
        bookId: bookId.value,
        pageIds: '',
        canDel: true,
        canEdit: true,
        canDrag: true,
        sort: node.children.length + 1,
        children: []
    }

    addMenu(newChild).then((data:any) => {
      console.log("添加孩子:", data);
      newChild.id=data.id
      node.children.push(newChild)
      ElMessage({message: '节点添加成功',type: 'success',})
    });
    // node.children.push(newChild)
}

/**编辑节点 */
const editNode = (node: BookMenu) => {
    // editingNode.value = treeRef.value!.getCurrentNode()
    editingNode.value = node;
    dialogNodeEditVisible.value = true
    thisPages.value.forEach((element: any) => {
        element.selected = editingNode.value.pageIds.includes(element.id);
    })
}

/**删除节点 */
const delNode = (node: any, data: BookMenu) => {
    // let node = treeRef.value!.getCurrentNode()
    let submitNodeArr = []
    submitNodeArr.push(data)
    console.log("需要提交的数据:", submitNodeArr)
    delMenu(submitNodeArr).then((r: any) => {
        treeRef.value!.getNode(data.id).remove()
        ElMessage({ message: '删除成功', type: 'success', })
    });
}

/** 拖拽结束 */
const handleDragEnd = (
    draggingNode: TreeNode,
    dropNode: TreeNode,
    dropType: NodeDropType,
    ev: DragEvent
) => {
    console.log('拖拽结束: 拖动的节点：', draggingNode, " 目标节点：", dropNode, "  位置：", dropType)
    let submitNodeArr = []
    if (dropType == "before" || dropType == "after") {
        //如果是目标节点的前后，则他们有共同的父亲，移动后把兄弟间的顺序（sort）重新计算
        draggingNode.data.pid = dropNode.data.pid   //父节点相同
        // 找到目标节点的父亲，把兄弟节点重新计算sort
        let parentNode = dropNode.parent!.data
        for (let i = 0; i < parentNode.children.length; i++) {
            parentNode.children[i].sort = i + 1
            submitNodeArr.push(parentNode.children[i])
        }
    } else if (dropType == "inner") {
        // 如果是移动到目标节点的里面，说明当下目标节点没有孩子，则其父亲为目标节点，移动后把兄弟间的顺序（sort）重新计算
        draggingNode.data.pid = dropNode.data.id
        for (let i = 0; i < dropNode.data.children.length; i++) {
            dropNode.data.children[i].sort = i + 1
            submitNodeArr.push(dropNode.data.children[i])
        }
    }
    console.log("需要提交的数据:", submitNodeArr)
    updateMenu(submitNodeArr).then((data: any) => {
        ElMessage({ message: '更新成功', type: 'success', })
    });
}

const allowDrop = (draggingNode: any, dropNode: any, type: AllowDropType) => {
    return dropNode.data.canDrag;
}

/** 计算当前节点的页码 */
const pageNumbers = (data: BookMenu) => {
    let nums: string[] = []
    thisPages.value.forEach((item) => {
        let ids=data.pageIds.split(',');
        if (ids.includes(item.id+'')) {
            nums.push(item.pageNum)
        }
    })
    return nums;
}

/** 页码点击事件 */
const onPageClick = (page: CheckerPage) => {
    page.selected = !page.selected;
    
    let ids: number[]=[]
    thisPages.value.forEach((element) => {
        if (element.selected) {
            ids.push(element.id)
        }
    })
    editingNode.value.pageIds = ids.join()
    console.log("保存节点：", editingNode.value);
}

const dialogSubmit = () => {
    console.log("保存节点：", editingNode.value);
    dialogNodeEditVisible.value = false;
    let submitNodeArr = []
    submitNodeArr.push(editingNode.value)
    console.log("需要提交的数据:", submitNodeArr)
    updateMenu(submitNodeArr).then((data: any) => {
        ElMessage({ message: '更新成功', type: 'success', })
    });
}
</script>
<style scoped lang="scss">
:deep(.el-tree) {
  background: none;

  .el-tree-node__content{
    background-color: #333;
    color:#fff;
    height:40px;
    margin-bottom: 1px;
  }
  
}
:deep(.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content){
    background-color: #666;
  }

::-webkit-scrollbar {
    width: 5px;
    /*  宽度  */
}

/* 设置滑块的样式 */
::-webkit-scrollbar-thumb {
    background-color: #666;
    /*  背景颜色  */
    border-radius: 5px;
    /*  圆角半径  */
}

/* 设置轨道的样式 */
::-webkit-scrollbar-track {
    background-color: #333;
    /*  背景颜色  */
}

/* 设置角落的样式 */
::-webkit-scrollbar-corner {
    background-color: #666;
    /*  背景颜色  */
}
</style>
